package com.eric.demo.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author guangyin.zhang
 * @since 2020/1/16
 */
public class LoopPrintTest2 {

    public static void main(String[] argvs){
        int maxNum = 29;
        AtomicInteger currentNum = new AtomicInteger(0);

        Thread threadX = new Thread(new PrintThread(maxNum, currentNum, 0, 3, "X"));
        threadX.setName("打印线程X");
        threadX.start();

        Thread threadY = new Thread(new PrintThread(maxNum, currentNum, 1, 3, "Y"));
        threadY.setName("打印线程Y");
        threadY.start();

        Thread threadZ = new Thread(new PrintThread(maxNum, currentNum, 2, 3, "Z"));
        threadZ.setName("打印线程Z");
        threadZ.start();

    }

    static class PrintThread implements Runnable{

        private int maxNum;

        private AtomicInteger currentNum;

        private int threadId;

        private int threadNum;

        private String str;

        public PrintThread(int maxNum, AtomicInteger currentNum, int threadId, int threadNum, String str) {
            this.maxNum = maxNum;
            this.currentNum = currentNum;
            this.threadId = threadId;
            this.threadNum = threadNum;
            this.str = str;
        }

        @Override
        public void run() {
            try {
                synchronized (currentNum) {
                    while (this.currentNum.get() <= this.maxNum){
                        currentNum.notifyAll();
                        if(this.currentNum.get() % threadNum == threadId){
                            System.out.print(this.str);
                            currentNum.getAndAdd(1);
                        }
                        currentNum.wait();
                    }
                    currentNum.notifyAll();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
